import { ImageAsset, sys, Texture2D } from "cc";
import { ChatBoxView } from "../../view/ChatBoxView";
declare var wx: any

class NetMgr {
    private readonly API_BASE_URL = '';
    private readonly APP_KEY = '';
    private readonly APP_SECRET = '';
    private readonly TENANT_ID = '1001';
    async fetchGet(baseUrl, params = {}): Promise<any> {
        // 构建查询字符串
        // 手动构建查询字符串
        let queryString = '';
        let isFirstParam = true;

        // 添加所有参数
        for (const key in params) {
            if (params.hasOwnProperty(key)) {
                // 对参数值进行 URI 编码
                const encodedValue = encodeURIComponent(params[key]);

                // 添加 ? 或 & 分隔符
                if (isFirstParam) {
                    queryString += '?';
                    isFirstParam = false;
                } else {
                    queryString += '&';
                }

                // 添加参数键值对
                queryString += `${encodeURIComponent(key)}=${encodedValue}`;
            }
        }

        // 构建完整URL
        const url = baseUrl + queryString;

        // 使用 XMLHttpRequest 发送请求
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onload = function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const data = JSON.parse(xhr.responseText);
                        resolve(data);
                    } catch (e) {
                        reject(new Error('Invalid JSON response'));
                    }
                } else {
                    reject(new Error(`HTTP error! Status: ${xhr.status}`));
                }
            };
            xhr.onerror = function () {
                console.error('XHR error occurred');
                reject(new Error('Network error occurred'));
            };
            xhr.ontimeout = function () {
                reject(new Error('Request timeout'));
            };
            // 发送请求
            xhr.send();
        });
    }

    async post(url: string, data: any, headers?: HeadersInit): Promise<any> {
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    ...headers,
                },
                body: JSON.stringify(data),
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            console.log("cocos response==", response)

            const responseData = await response.json();
            return responseData;
        } catch (error) {
            console.error('Error:', error);
            throw error;
        }
    }

    public async sendRequest(url, jsonData): Promise<any> {
        console.log("cocos 请求开始==")

        return new Promise((resolve) => {
            const data = JSON.stringify(jsonData);
            console.log("cocos data==", data)
            const timer = setTimeout(() => {
                console.log('Request timed out');
                resolve(null); // 超时后解决Promise为null
            }, 15000);

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: data
            })
                .then(response => {
                    clearTimeout(timer); // 如果请求成功，则清除定时器
                    if (!response.ok) {
                        console.warn(`HTTP error ${response.status}+response`);
                        return null;
                    }
                    return response.json();
                })
                .catch(error => {
                    clearTimeout(timer); // 如果请求成功，则清除定时器
                    console.log("cocos error:" + error);
                    return null;
                })
                .then(resolve); // 无论成功还是失败都调用resolve
        });
    }
    public async WXsendRequest(url, jsonData): Promise<any> {
        return new Promise((resolve) => {
            const data = JSON.stringify(jsonData);
            const timer = setTimeout(() => {
                console.log('Request timed out');
                resolve(null); // 超时后解决Promise为null
            }, 12000);
            wx.request({
                url: url,
                method: 'POST',
                data: data,
                header: {
                    'Content-Type': 'application/json',
                },
                success(res) {
                    clearTimeout(timer); // 如果请求成功，则清除定时器
                    if (res.statusCode === 200) {
                        resolve(res.data); // 解析Promise为响应的数据
                    } else {
                        console.warn(`HTTP error ${res.statusCode}`);
                        resolve(null);
                    }
                },
                fail(error) {
                    clearTimeout(timer); // 如果请求失败，也清除定时器
                    console.error("error:" + error);
                    resolve(null);
                }
            });
        });
    }
    public async sendPost(url, jsonData): Promise<any> {
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: JSON.stringify(jsonData),
            });

            // 检查响应状态
            if (!response.ok) {
                console.warn(`HTTP error ${response.status}`);
                throw new Error('Network response was not ok.');
            }

            const ab = await response.json();

            return ab;
        } catch (error) {
            // 捕获网络错误等，并输出
            console.error("error:" + error);
            throw error; // 这里应该抛出错误让调用者知道发生了什么
        }
    }


    public async sendGptRequest(url, jsonData, apiKey, chatBox: ChatBoxView): Promise<any> {
        const chat = chatBox;
        console.log("Received sendGptRequest");

        return new Promise((resolve) => {
            const data = JSON.stringify(jsonData);

            // 使用XMLHttpRequest
            const xhr = new XMLHttpRequest();

            xhr.open('POST', url);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('Authorization', 'Bearer ' + apiKey);
            // 设置超时时间，单位为毫秒
            xhr.timeout = 90000;

            // 普通文本模式
            xhr.responseType = 'json';

            // 完成处理
            xhr.onload = () => {
                if (xhr.status >= 200 && xhr.status < 300) {
                    let responseText = '';

                    try {
                        const response = xhr.response;
                        console.log('Received response:', response);

                        // 检查不同的可能响应格式
                        if (response.choices && response.choices[0].message && response.choices[0].message.content) {
                            // 标准GPT完整响应格式
                            responseText = response.choices[0].message.content;
                        }


                        // 更新聊天内容
                        chat.updateContent(responseText);

                    } catch (e) {
                        console.warn('Failed to parse response:', e);

                        // 尝试将响应作为纯文本处理
                        if (xhr.responseText) {
                            responseText = xhr.responseText;
                            chat.updateContent(responseText);
                        }
                    }

                    resolve(responseText);
                } else {
                    console.warn(`HTTP error ${xhr.status}`);
                    resolve(null);
                }
            };

            // 错误处理
            xhr.onerror = (error) => {
                console.warn('Request failed:', error);
                resolve(null);
            };

            // 超时处理
            xhr.ontimeout = () => {
                console.log('Request timed out');
                resolve(null);
            };

            // 发送请求
            xhr.send(data);
        });
    }
    objectToQueryString(params: object) {
        let result = ""
        for (let key in params) {
            const value = params[key]
            result += `${key}=${value}&`
        }
        // result = result.slice(0, -1)
        return result
    }

    public blobToTex(blob: Blob): Promise<Texture2D> {
        return new Promise((resolve, reject) => {
            this.blobToImageData(blob).then((imageData: ImageData) => {
                this.imageDataToSprieFram(imageData).then((tex: Texture2D) => {
                    resolve(tex);
                });
            });
        });
    }

    blobToImageData(blob) {
        return new Promise((resolve, reject) => {
            const url = URL.createObjectURL(blob);
            const img = new Image();
            img.onload = () => {
                URL.revokeObjectURL(url);
                const canvas = document.createElement('canvas');
                canvas.width = img.width;
                canvas.height = img.height;
                const ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0);
                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                resolve(imageData);
            };
            img.onerror = reject;
            img.src = url;
        });
    }

    imageDataToSprieFram(imageData: ImageData) {
        return new Promise((resolve, reject) => {
            let imageAsset = new ImageAsset();
            imageAsset.reset({
                _data: imageData.data,
                width: imageData.width,
                height: imageData.height,
                format: Texture2D.PixelFormat.RGBA8888,
                _compressed: false,
            });
            const tex = new Texture2D();
            tex.image = imageAsset;

            resolve(tex);
        });
    }

    async createTextureFromBlob(blob): Promise<Texture2D> {
        return new Promise((resolve, reject) => {
            const image = new Image();
            image.onload = () => {
                const texture = new Texture2D();
                texture.uploadData(image);
                console.log("load image success")
                resolve(texture);  // 图片加载完成后，解析 Promise 并返回 texture
            };
            image.onerror = () => {
                reject(new Error("Failed to load image"));
            };
            image.src = URL.createObjectURL(blob);
        });
    }

    saveFile(fileBlob: any, fileNameToSaveAs: string) {
        if (sys.isBrowser) {
            // 假设binaryData是包含MP3二进制数据的ArrayBuffer或Uint8Array
            let downloadLink = document.createElement("a");
            downloadLink.download = fileNameToSaveAs;
            downloadLink.innerHTML = "Download File";
            if (window.webkitURL != null) {
                // Chrome allows the link to be clicked
                // without actually adding it to the DOM.
                downloadLink.href = window.webkitURL.createObjectURL(fileBlob);
            }
            else {
                // Firefox requires the link to be added to the DOM
                // before it can be clicked.
                downloadLink.href = window.URL.createObjectURL(fileBlob);
                downloadLink.style.display = "none";
                document.body.appendChild(downloadLink);
            }
            downloadLink.click();

            // Optional: remove the link after triggering the download
            downloadLink.remove();
        }
    }

    /**
    * 上传图片并获取识别结果
    * @param base64Image base64编码的图片数据
    * @returns 返回接口识别结果
    */
    public async recognizeDrawing(base64Image: string): Promise<any> {

        try {
            if (!base64Image) {
                throw new Error('图片数据不能为空');
            }

            // 确保base64字符串包含前缀
            if (!base64Image.startsWith('data:image')) {
                console.warn('Base64字符串没有正确的前缀，可能导致识别失败');
            }

            // 步骤1: 获取权限token
            const authResult = await this.getAccessToken();
            console.log('cocos 获取权限token成功:', authResult.data.accessToken);

            // 步骤2: 获取接口token
            const interfaceToken = await this.getInterfaceToken(authResult.data.accessToken);
            console.log('cocos 获取接口token成功:', interfaceToken);

            // 步骤3: 上传图片进行识别
            const recognitionResult = await this.uploadImageForRecognition(
                authResult.data.accessToken,
                interfaceToken,
                base64Image
            );

            const data = recognitionResult.data;
            const roomData = JSON.parse(data.roomContent)

            console.log('cocos 图纸识别结果:', roomData);


            return roomData;
        } catch (error) {
            console.error('cocos 识别图纸过程中发生错误:', error);
            throw null;
        }
    }

    /**
     * 步骤1: 获取权限token
     */
    private async getAccessToken(): Promise<any> {
        try {
            const url = `${this.API_BASE_URL}/mibp-basic-application/v1/basic/get/access/token`;
            const requestBody = {
                appKey: this.APP_KEY,
                appSecret: this.APP_SECRET,
                tenantId: this.TENANT_ID
            };

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestBody)
            });

            if (!response.ok) {
                throw new Error(`获取权限token失败: ${response.status} ${response.statusText}`);
            }

            const data = await response.json();
            if (!data.success) {
                throw new Error(`获取权限token请求成功但返回错误: ${data.errorMsg}`);
            }

            return data;
        } catch (error) {
            console.error('获取权限token失败:', error);
            throw error;
        }
    }
    /**
    * 步骤3: 上传图片进行识别
    * @param accessToken 步骤1获取的访问令牌
    * @param interfaceToken 步骤2获取的接口令牌
    * @param base64Image base64编码的图片数据
    */
    private async uploadImageForRecognition(
        accessToken: string,
        interfaceToken: string,
        base64Image: string
    ): Promise<any> {
        try {
            const url = `${this.API_BASE_URL}/mibp-basic-message/v2/message/modelData`;

            const requestBody = {
                accessToken: interfaceToken,
                imageData: base64Image
            };

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Access-Token': accessToken
                },
                body: JSON.stringify(requestBody)
            });

            if (!response.ok) {
                throw new Error(`识别图纸失败: ${response.status} ${response.statusText}`);
            }

            const recognitionResult = await response.json();
            return recognitionResult;
        } catch (error) {
            console.error('识别图纸失败:', error);
            throw error;
        }
    }

    /**
     * 步骤2: 获取接口token
     * @param accessToken 步骤1获取的访问令牌
     */
    private async getInterfaceToken(accessToken: string): Promise<string> {
        try {
            const url = this.API_BASE_URL + `/mibp-basic-message/v2/message/accessToken`;

            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Access-Token': accessToken
                }
            });

            if (!response.ok) {
                console.error(`请求失败，状态码: ${response.status}`);
                return;
            }

            const text = await response.text();
            return text;
        } catch (error) {
            console.error('获取接口token失败:', error);
            throw error;
        }
    }


}
const Net = new NetMgr;

export default Net;
